<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <VideoContent class="video-flex-item" v-for="item, index in caremaList"  :rootId="item.rootId + index"  :videoId="item.videoId + index"
      :canvasId="item.canvasId + index" :startTime="item.startTime" :name="item.name" :caramObj="item.caramObj"
      :deviceObj="item.deviceObj" :hasTitle="item.hasTitle" :hasAction="item.hasAction" :history="true"
      :cameraPlaybackObj="item.cameraPlaybackObj" :width="660"></VideoContent>

  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, onMounted } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { diviceList } from '../Violation.api';
import VideoContent from '../../videotape/components/VideoContent.vue'

import NvrRpc from '../../videotape/rpc.js'
import dayjs from 'dayjs';
let caremaList = ref([])
let isLogin = ref(false);//nvr是否登录
let deviceObj = ref({
  ip: '',
  username: '',
  password: '',
  port: ''
})//设备nvr的信息
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter, minHeight: 400, defaultFullscreen: false, canFullscreen: true });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.showFooter;
  console.log(data.record.violationTime)
  let startTime = dayjs(data.record.violationTime).unix() - 60 * 2;
  let endTime = dayjs(data.record.violationTime).unix();
  let range = endTime - startTime;
  let startTimeString = dayjs.unix(startTime).format("YYYY-MM-DD HH:mm:ss")
  let endTimeString = dayjs.unix(endTime).format("YYYY-MM-DD HH:mm:ss")
  if (isLogin.value) {
    getCameraAll({ ip: data.record.equipment.ip, startTime: startTimeString, endTime: endTimeString, range }, data.record.equipment, endTime, data.record.violationTime)
  } else {
    await getDiviceList();
    getCameraAll({ ip: data.record.equipment.ip, startTime: startTimeString, endTime: endTimeString, range }, data.record.equipment, endTime, data.record.violationTime);
  }

});
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));
/**
 * 获取所有的通道，码流
 */
const getCameraAll = ({ ip, startTime, endTime, range }, equipment, time, violationTime) => {
  NvrRpc.getCameraAll().then(res => {
    if (res && res.length > 0) {
      for (const item of res) {
        if (item.DeviceInfo && item.DeviceInfo.Address == ip && item.Enable) {
          searchRecord({ cameraChannel: item.UniqueChannel, startTime, endTime, range }, equipment, time, violationTime)
        }
      }
    }
  })
}
const searchRecord = (params, equipment, time, violationTime) => {
  console.log("params====", params);

  NvrRpc.searchRecord(params).then(res => {
    let data = res.map((item, index) => {
      let timeNum = time - dayjs(item.StartTime).unix();
      console.log("测试===", timeNum);

      return {
        name: dayjs(item.StartTime).format('HH:mm:ss') + ' - ' + dayjs(item.EndTime).format('HH:mm:ss'),
        videoId: 'videoId',
        canvasId: 'canvasId',
        rootId:'rootId',
        caramObj: {
          ip: equipment.ip,
          port: equipment.port,
          username: equipment.username,
          password: equipment.password,
        },
        deviceObj: unref(deviceObj),
        hasAction: true,
        hasTitle: true,
        cameraPlaybackObj: { ...item, ...{ playbackIndex: 0, time: timeNum, violationTime } },

      }
    })
    caremaList.value = data;
    console.log("成功：：", data)

  }).catch(err => {
    console.log("异常：：", err)
  })
}
const onPercentChange = (e) => {
  console.log("eeee", e)
}
/**
* 获取NVR的配置
*/
const getDiviceList = async () => {
  let result = await diviceList({
    category: 'dvr'
  });
  if (result.records && result.records.length > 0) {
    deviceObj.value = {
      ip: result.records[0].ip,
      port: result.records[0].port,
      username: result.records[0].username,
      password: result.records[0].password
    }
  }
  let res = await NvrRpc.logIn({
    ip: deviceObj.value.ip,
    port: deviceObj.value.port,
    username: deviceObj.value.username,
    password: deviceObj.value.password
  })
  isLogin.value = res?.result;
}
onMounted(async () => {
  await getDiviceList();
})
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}

.video-flex-item {
  height: 390px;
}
</style>